import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getRelativeList, getRelativeListBasic, getRelativeProfile } from '@/api/pc/elderly'

export const useRelativeStore = defineStore('relative', () => {
  // 本地持久化键名
  const STORAGE_KEYS = {
    avatars: 'relative_store_avatars_v1',
    fullData: 'relative_store_fullData_v1'
  }

  // 运行环境与本地存储可用性守护
  const IS_PROD = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'production'
  const STORAGE_ENABLED = typeof localStorage !== 'undefined'

  const currentRelativeId = ref(null)
  const list = ref([])
  const loading = ref(false)
  const error = ref('')
  const avatarLoading = ref(false) // 头像加载状态
  
  // 智能缓存系统
  const cache = ref({
    // 基础列表缓存（轻量级）
    basicList: {
      data: [],
      timestamp: 0,
      ttl: 5 * 60 * 1000, // 5分钟
      userId: null
    },
    // 头像URL缓存（永久）
    avatars: new Map(),
    // 详情数据缓存（永久）
    details: new Map(),
    // 完整数据缓存
    fullData: {
      data: [],
      timestamp: 0,
      ttl: 10 * 60 * 1000, // 10分钟
      userId: null
    }
  })

  // —— 本地存储：加载/保存 ——
  function loadAvatarsFromStorage() {
    if (!STORAGE_ENABLED) return
    try {
      const raw = localStorage.getItem(STORAGE_KEYS.avatars)
      if (!raw) return
      const entries = JSON.parse(raw)
      if (Array.isArray(entries)) cache.value.avatars = new Map(entries)
    } catch (_) {}
  }

  function saveAvatarsToStorage() {
    if (!STORAGE_ENABLED) return
    try {
      const entries = Array.from(cache.value.avatars.entries())
      localStorage.setItem(STORAGE_KEYS.avatars, JSON.stringify(entries))
    } catch (_) {}
  }

  function loadFullDataFromStorage() {
    if (!STORAGE_ENABLED) return
    try {
      const raw = localStorage.getItem(STORAGE_KEYS.fullData)
      if (!raw) return
      const obj = JSON.parse(raw)
      if (obj && Array.isArray(obj.data)) {
        cache.value.fullData = {
          data: obj.data,
          timestamp: obj.timestamp || 0,
          ttl: obj.ttl || cache.value.fullData.ttl,
          userId: obj.userId || null
        }
        // 同步首屏
        list.value = obj.data
      }
    } catch (_) {}
  }

  function saveFullDataToStorage() {
    if (!STORAGE_ENABLED) return
    try {
      const payload = {
        data: cache.value.fullData.data,
        timestamp: cache.value.fullData.timestamp,
        ttl: cache.value.fullData.ttl,
        userId: cache.value.fullData.userId
      }
      localStorage.setItem(STORAGE_KEYS.fullData, JSON.stringify(payload))
    } catch (_) {}
  }

  function clearPersistentStorage() {
    if (!STORAGE_ENABLED) return
    try {
      localStorage.removeItem(STORAGE_KEYS.avatars)
      localStorage.removeItem(STORAGE_KEYS.fullData)
    } catch (_) {}
  }

  // 初始化恢复
  loadAvatarsFromStorage()
  loadFullDataFromStorage()
 
  // 获取缓存的头像URL
  function getCachedAvatarUrl(role, overwrite = false) {
    const roleId = role?.id ?? role?.relativeId ?? role?.rid
    if (!roleId) return '/static/images/p1.png'
    
    // 检查缓存
    if (!overwrite && cache.value.avatars.has(roleId)) {
      return cache.value.avatars.get(roleId)
    }
    
    // 计算头像URL
    let avatarUrl = '/static/images/p1.png'
    
    if (role.personalityProfile && Array.isArray(role.personalityProfile) && role.personalityProfile.length > 0) {
      const firstProfile = role.personalityProfile[0]
      if (firstProfile.fileBase64) {
        if (firstProfile.fileBase64.startsWith('data:')) {
          avatarUrl = firstProfile.fileBase64
        } else {
          const mimeType = firstProfile.mimeType || 'image/png'
          avatarUrl = `data:${mimeType};base64,${firstProfile.fileBase64}`
        }
        // 缓存结果并持久化（覆盖或新增）
        cache.value.avatars.set(roleId, avatarUrl)
        saveAvatarsToStorage()
      }
    }
    
    return avatarUrl
  }

  // 计算属性：获取处理后的列表数据
  const processedList = computed(() => {
    return list.value.map(role => ({
      ...role,
      // 预计算头像URL
      avatarUrl: getCachedAvatarUrl(role),
      // 标记是否有完整数据
      hasFullData: cache.value.details.has(role.id || role.relativeId || role.rid)
    }))
  })

  function setCurrentRelativeId(id) {
    currentRelativeId.value = id
  }

  // 检查缓存是否有效
  function isCacheValid(cacheKey, ttl) {
    const now = Date.now()
    const cacheData = cache.value[cacheKey]
    return cacheData && 
           cacheData.data && 
           cacheData.data.length > 0 && 
           (now - cacheData.timestamp) < ttl
  }

  // 获取基础列表（轻量级，不包含文件数据）
  async function fetchList(userId, forceRefresh = false) {
    if (!userId) {
      list.value = []
      return
    }
    
    // 检查基础列表缓存
    if (!forceRefresh && isCacheValid('basicList', cache.value.basicList.ttl) && 
        cache.value.basicList.userId === userId) {
      list.value = cache.value.basicList.data
      return
    }
    
    loading.value = true
    error.value = ''
    try {
      const res = await getRelativeListBasic(userId)
      const rows = res?.rows || []
      
      // 更新基础列表缓存
      cache.value.basicList = {
        data: rows,
        timestamp: Date.now(),
        ttl: cache.value.basicList.ttl,
        userId: userId
      }
      
      list.value = rows
    } catch (e) {
      error.value = e?.msg || '加载亲属列表失败'
      list.value = []
    } finally {
      loading.value = false
    }
  }

  // 获取主页列表（分步加载：先显示基础信息，后加载头像）
  async function fetchHomeList(userId, forceRefresh = false) {
    if (!userId) {
      list.value = []
      return
    }
    
    // 检查完整数据缓存（如果已有完整数据，直接使用）
    if (!forceRefresh && isCacheValid('fullData', cache.value.fullData.ttl) && 
        cache.value.fullData.userId === userId) {
      list.value = cache.value.fullData.data
      return
    }
    
    loading.value = true
    error.value = ''
    
    try {
      // 第一步：快速加载基础列表（不包含头像）
      const basicRes = await getRelativeListBasic(userId)
      const basicRows = basicRes?.rows || []
      
      // 立即显示基础列表
      list.value = basicRows
      loading.value = false
      
      // 第二步：异步加载完整数据（包含头像）
      avatarLoading.value = true
      try {
        const fullRes = await getRelativeList(userId)
        const fullRows = fullRes?.rows || []
        
        // 更新完整数据缓存
        cache.value.fullData = {
          data: fullRows,
          timestamp: Date.now(),
          ttl: cache.value.fullData.ttl,
          userId: userId
        }
        saveFullDataToStorage()
        
        // 更新列表为完整数据（包含头像）
        list.value = fullRows
        
        // 预加载头像到缓存（覆盖旧缓存，确保刷新后生效）
        if (fullRows.length > 0) {
          // 立即处理头像URL并缓存
          fullRows.forEach(role => {
            const avatarUrl = getCachedAvatarUrl(role, true)
          })
          saveAvatarsToStorage()
        }
      } catch (fullError) {
        console.warn('加载完整数据失败，使用基础数据:', fullError)
        // 如果完整数据加载失败，保持基础数据显示
      } finally {
        avatarLoading.value = false
      }
      
    } catch (e) {
      error.value = e?.msg || '加载亲属列表失败'
      list.value = []
      loading.value = false
    }
  }

  // 获取完整列表（包含文件数据）
  async function fetchFullList(userId, forceRefresh = false) {
    if (!userId) {
      list.value = []
      return
    }
    
    // 检查完整数据缓存
    if (!forceRefresh && isCacheValid('fullData', cache.value.fullData.ttl) && 
        cache.value.fullData.userId === userId) {
      list.value = cache.value.fullData.data
      return
    }
    
    loading.value = true
    error.value = ''
    try {
      const res = await getRelativeList(userId)
      const rows = res?.rows || []
      
      // 更新完整数据缓存
      cache.value.fullData = {
        data: rows,
        timestamp: Date.now(),
        ttl: cache.value.fullData.ttl,
        userId: userId
      }
      saveFullDataToStorage()
      
      list.value = rows
    } catch (e) {
      error.value = e?.msg || '加载亲属完整列表失败'
      list.value = []
    } finally {
      loading.value = false
    }
  }

  // 懒加载：获取单个角色详情（使用现有的 getRelativeProfile）
  async function fetchRelativeDetail(relativeId) {
    if (!relativeId) return null
    
    // 检查缓存
    if (cache.value.details.has(relativeId)) {
      return cache.value.details.get(relativeId)
    }
    
    try {
      const res = await getRelativeProfile(relativeId)
      if (res && res.data) {
        // 缓存详情数据
        cache.value.details.set(relativeId, res.data)
        return res.data
      }
    } catch (e) {
      console.warn('Failed to fetch relative detail:', e)
    }
    return null
  }

  // 预加载头像（懒加载）
  async function preloadAvatars(roles) {
    const promises = roles.map(async (role) => {
      const roleId = role?.id ?? role?.relativeId ?? role?.rid
      if (!roleId || cache.value.avatars.has(roleId)) return
      
      // 如果角色有完整数据，直接计算头像
      if (role.personalityProfile && role.personalityProfile.length > 0) {
        getCachedAvatarUrl(role)
      } else {
        // 否则懒加载详情数据
        const detail = await fetchRelativeDetail(roleId)
        if (detail) {
          getCachedAvatarUrl(detail)
        }
      }
    })
    
    await Promise.all(promises)
  }

  // 清除缓存
  function clearCache() {
    cache.value.basicList = { data: [], timestamp: 0, ttl: cache.value.basicList.ttl, userId: null }
    cache.value.fullData = { data: [], timestamp: 0, ttl: cache.value.fullData.ttl, userId: null }
    cache.value.avatars.clear()
    cache.value.details.clear()
    list.value = []
    clearPersistentStorage()
  }

  // 清除指定用户的缓存
  function clearUserCache(userId) {
    if (cache.value.basicList.userId === userId) {
      cache.value.basicList = { data: [], timestamp: 0, ttl: cache.value.basicList.ttl, userId: null }
    }
    if (cache.value.fullData.userId === userId) {
      cache.value.fullData = { data: [], timestamp: 0, ttl: cache.value.fullData.ttl, userId: null }
      if (STORAGE_ENABLED) {
        try { localStorage.removeItem(STORAGE_KEYS.fullData) } catch (_) {}
      }
    }
  }

// 添加一个方法来处理角色删除后的缓存清理
  function removeRelativeFromCache(relativeId) {
    if (!relativeId) return;
    
    // 清除头像缓存
    cache.value.avatars.delete(relativeId);
    
    // 清除详情缓存
    cache.value.details.delete(relativeId);
    
    // 从基础列表缓存中移除
    if (cache.value.basicList.data) {
      cache.value.basicList.data = cache.value.basicList.data.filter(
        item => (item.relativeId || item.id || item.rid) !== relativeId
      );
    }
    
    // 从完整数据缓存中移除
    if (cache.value.fullData.data) {
      cache.value.fullData.data = cache.value.fullData.data.filter(
        item => (item.relativeId || item.id || item.rid) !== relativeId
      );
    }
    
    // 从当前列表中移除
    list.value = list.value.filter(
      item => (item.relativeId || item.id || item.rid) !== relativeId
    );
    
    // 保存更新后的缓存到localStorage
    saveAvatarsToStorage();
    saveFullDataToStorage();
  }

  return {
    currentRelativeId,
    list,
    processedList,
    loading,
    avatarLoading,
    error,
    setCurrentRelativeId,
    fetchList,
    fetchHomeList,
    fetchFullList,
    fetchRelativeDetail,
    preloadAvatars,
    clearCache,
    clearUserCache,
    getCachedAvatarUrl,
    removeRelativeFromCache
  }
})
